//
//  ProductCenterWarwHouseView.m
//  WholesalerApp
//
//  Created by macox on 16/11/2.
//  Copyright © 2016年 macox. All rights reserved.
//

#import "ProductCenterWarwHouseView.h"
#import "ProductModel.h"
#import "ProductCenterWareTableViewCell.h"
#import "EditProductViewController.h"
#import "UIView+UIViewController.h"
//#import "ReleaseCommoditySubModel.h"


@implementation ProductCenterWarwHouseView
{
    NSMutableArray *ChanelDataArray;//接收数组;
    NSInteger pageNumber;//
    NSMutableArray *_goodDataListRefresh;//
    NSString *couponIDS;
    UITextField *modifyNumberText;
    
}
- (id)initWithFrame:(CGRect)frame{
    
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tongzhi:) name:@"tongzhi" object:nil];
    if (self = [super initWithFrame:frame]) {
           pageNumber = 1;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        [self createCommodityWarehouseViewTableView];
        [self commodityLibraryInformationDataRequest];
    }
    return self;
}

#pragma mark --  创建tableview
- (void)createCommodityWarehouseViewTableView{
    
    _CommodityWView =[[UITableView alloc]initWithFrame:CGRectMake(0,0,kScrernWidth-90,kScrernHeight-164) style:UITableViewStylePlain];
    _CommodityWView.showsVerticalScrollIndicator = FALSE;
    _CommodityWView.delegate=self;
    _CommodityWView.dataSource=self;
    _CommodityWView.backgroundColor = [UIColor colorWithHue:0.00 saturation:0.00 brightness:0.94 alpha:1.00];
    _CommodityWView.tableFooterView = [[UIView alloc] init];
    [self addSubview:_CommodityWView];
    
    

}
- (void)tongzhi:(NSNotification *)text{
    
    NSLog(@"=====-----%@",text.userInfo[@"textOne"]);
    
    NSLog(@"－－－－－接收到通知------");
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_data_array count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifer=@"commodityCell";
    ProductCenterWareTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ProductCenterWareTableViewCell" owner:nil options:nil] firstObject];
    }
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_data_array.count != 0) {
        ProductModel *model = [_data_array objectAtIndex:indexPath.row];
        cell.model = model;
    }
    return cell;
}
- (void)keyboardWillShow:(NSNotification *)notification {
    /*
     Reduce the size of the text view so that it's not obscured by the keyboard.
     Animate the resize so that it's in sync with the appearance of the keyboard.
     */
    NSDictionary *userInfo = [notification userInfo];
    // Get the origin of the keyboard when it's displayed.
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self convertRect:keyboardRect fromView:nil];
    
    CGFloat keyboardTop = keyboardRect.origin.y;
    CGRect tableViewFrame = self.bounds;
    tableViewFrame.size.height = keyboardTop - self.bounds.origin.y;
    
    // Get the duration of the animation.
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    // Animate the resize of the text view's frame in sync with the keyboard's appearance.
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    
    _addNumberView.frame = CGRectMake(kScrernWidth / 10 - 30,  30,kScrernWidth / 2  + 65 , 120);
    [UIView commitAnimations];
}
- (void)keyboardWillHide:(NSNotification *)notification {
    
    NSDictionary* userInfo = [notification userInfo];
    /*
     Restore the size of the text view (fill self's view).
     Animate the resize so that it's in sync with the disappearance of the keyboard.
     */
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    _addNumberView.frame= CGRectMake(kScrernWidth / 10 - 30,  90,kScrernWidth / 2  + 65 , 120);
    [UIView commitAnimations];
}
#pragma mark -- 编辑
- (void)trunEditGroundingVC:(NSString *)ProID :(NSString *)MaeketPriceString :(NSString *)StockString{
    _couponIDS = ProID;
    [self editViewNum:MaeketPriceString :StockString];
}
#pragma mark -- 编辑界面
- (void)editViewNum:(NSString *)MaeketPriceString:(NSString *)StockString{
    
    //    couponIDS = couponID;
    _addNumberView = [[UIView alloc]initWithFrame:CGRectMake(kScrernWidth / 10 - 30,  90,kScrernWidth / 2  + 65 , 120)];
    _addNumberView.backgroundColor = [UIColor whiteColor];
    _addNumberView.layer.cornerRadius = 8;
    
    _addNumberView.layer.masksToBounds = YES;
    //给图层添加一个有色边框
    
    _addNumberView.layer.borderWidth = 0.5;
    
    _addNumberView.layer.borderColor = [[UIColor grayColor] CGColor];
    
    [self addSubview: _addNumberView];
    
    
    
    UILabel *modifyMarkLabel = [[UILabel alloc]initWithFrame:CGRectMake(_addNumberView.frame.size.width / 2  - 100, 13, 50, 30)];
    modifyMarkLabel.text = @"市场价格";
    modifyMarkLabel.textColor = [UIColor colorWithRed:0.30 green:0.30 blue:0.30 alpha:1.00];
    //        modifyLabel.backgroundColor = [UIColor blackColor];
    modifyMarkLabel.font = [UIFont systemFontOfSize:12];
    [_addNumberView addSubview:modifyMarkLabel];
    
    _modifyMarkNumberText = [[UITextField alloc]initWithFrame:CGRectMake(modifyMarkLabel.frame.origin.x +modifyMarkLabel.frame.size.width + 20, modifyMarkLabel.frame.origin.y, 100, 30)];
    _modifyMarkNumberText.backgroundColor =[UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.00];
    _modifyMarkNumberText.delegate = self;
    _modifyMarkNumberText.font = [UIFont systemFontOfSize:14];
    _modifyMarkNumberText.text = MaeketPriceString;
    _modifyMarkNumberText.borderStyle = UITextBorderStyleRoundedRect;
    [_addNumberView addSubview:_modifyMarkNumberText];
    
    
    
    
    
    UILabel *modifyLabel = [[UILabel alloc]initWithFrame:CGRectMake(_addNumberView.frame.size.width / 2  - 100, modifyMarkLabel.frame.origin.y + modifyMarkLabel.frame.size.height + 5, 50, 30)];
    modifyLabel.text = @"库存";
    modifyLabel.textColor = [UIColor colorWithRed:0.30 green:0.30 blue:0.30 alpha:1.00];
    //   modifyLabel.backgroundColor = [UIColor blackColor];
    modifyLabel.font = [UIFont systemFontOfSize:12];
    [_addNumberView addSubview:modifyLabel];

    _modifyNumberText = [[UITextField alloc]initWithFrame:CGRectMake(modifyLabel.frame.origin.x +modifyLabel.frame.size.width + 20, modifyLabel.frame.origin.y, 100, 30)];
    _modifyNumberText.backgroundColor =[UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.00];
    _modifyNumberText.delegate = self;
    _modifyNumberText.font = [UIFont systemFontOfSize:14];
    _modifyNumberText.borderStyle = UITextBorderStyleRoundedRect;
    _modifyNumberText.text = StockString;
    [_addNumberView addSubview:_modifyNumberText];
    
    
    
    
//    UILabel *modifyNumberLine = [[UILabel alloc]initWithFrame:CGRectMake(_addNumberView.frame.size.width / 2  - 100, modifyMarkLabel.frame.origin.y + modifyMarkLabel.frame.size.height + 5, 50, 30)];
//    modifyNumberLine.text = @"库存";
//    modifyNumberLine.textColor = [UIColor colorWithRed:0.30 green:0.30 blue:0.30 alpha:1.00];
//    //    modifyNumberLine.backgroundColor = [UIColor blueColor];
//    modifyNumberLine.font = [UIFont systemFontOfSize:12];
//    [_addNumberView addSubview:modifyNumberLine];
//    
//    _modifykuChunNumberText = [[UITextField alloc]initWithFrame:CGRectMake(_modifyNumberText.frame.origin.x , modifyNumberLine.frame.origin.y ,100, 30)];
//    _modifykuChunNumberText.backgroundColor =[UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.00];
//    _modifykuChunNumberText.delegate = self;
//    _modifykuChunNumberText.text = StockString;
//    _modifykuChunNumberText.borderStyle = UITextBorderStyleRoundedRect;
//    _modifykuChunNumberText.font = [UIFont systemFontOfSize:14];
//    [_addNumberView addSubview:_modifykuChunNumberText];
    
    
    
    
    UIButton * makeSureCouponButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [makeSureCouponButton addTarget:self action:@selector(makeSureCouponAction) forControlEvents:UIControlEventTouchUpInside];
    
    [makeSureCouponButton setTitle:@"确定" forState:UIControlStateNormal];
    makeSureCouponButton.titleLabel.font = [UIFont systemFontOfSize: 15];
    [makeSureCouponButton  setTitleColor:[UIColor colorWithRed:0.35 green:0.35 blue:0.35 alpha:1.00] forState:UIControlStateNormal];
    makeSureCouponButton.frame = CGRectMake(0,_addNumberView.frame.size.height - 30,_addNumberView.frame.size.width / 2 - 2,30);
    
    
    makeSureCouponButton.layer.borderColor = [[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00] CGColor];
    
    makeSureCouponButton.layer.borderWidth = 1.0f;
    
    //给按钮设置弧度,这里将按钮变成了圆形
    makeSureCouponButton.layer.masksToBounds = YES;
    
    [_addNumberView addSubview:makeSureCouponButton];
    
    
    
    UIButton * delectCouponButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [delectCouponButton addTarget:self action:@selector(delectCouponAction) forControlEvents:UIControlEventTouchUpInside];
    [delectCouponButton setTitle:@"取消" forState:UIControlStateNormal];
    delectCouponButton.titleLabel.font = [UIFont systemFontOfSize: 15];
    [delectCouponButton  setTitleColor:[UIColor colorWithRed:0.35 green:0.35 blue:0.35 alpha:1.00] forState:UIControlStateNormal];
    delectCouponButton.frame = CGRectMake(makeSureCouponButton.frame.size.width + 1,_addNumberView.frame.size.height - 30,_addNumberView.frame.size.width / 2 - 1,30);
    delectCouponButton.backgroundColor = [UIColor whiteColor];
    
    
    delectCouponButton.layer.borderColor = [[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00] CGColor];
    
    delectCouponButton.layer.borderWidth = 1.0f;
    
    //给按钮设置弧度,这里将按钮变成了圆形
    delectCouponButton.layer.masksToBounds = YES;
    
    
    
    [_addNumberView addSubview:delectCouponButton];
    _addNumberViewAll  = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScrernWidth, kScrernHeight - 50)];
    [_addNumberViewAll addSubview:_addNumberView];
    [self addSubview:_addNumberViewAll];
    
    
    
}
#pragma mark -- 确定
- (void)makeSureCouponAction{
    //    [SVProgressHUD showWithStatus:@"正在加载"];
    NSDictionary *param = @{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN,@"CpId":_couponIDS,@"MakerPrice":_modifyMarkNumberText.text,@"Sku":_modifyNumberText.text};
    
    NSLog(@"======00----0%@", param);
    [GDJHttpTool post:UpDataProduct params:param success:^(id responseObj) {
        
        NSLog(@"确%@", responseObj);
        NSLog(@"确定%@", param);
//        
//     [_CommodityWView reloadData];
        if ([[responseObj objectForKey:@"Err"] intValue]== 0) {
            [self commodityLibraryInformationDataRequest];
        }
        
    } failure:^(NSError *error) {
        
        NSLog(@"====%@",error);
    }];
    
    
    [_addNumberViewAll removeFromSuperview];
}
#pragma mark -- 取消
- (void)delectCouponAction{
    [_addNumberViewAll removeFromSuperview];
}


#pragma mark -- 删除
- (void)DeleteVC:(NSString *)ProductID{
    NSLog(@"删除");
    NSDictionary *param = @{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN,@"ProductId":ProductID,@"Operation":@"删除" };
    
    [GDJHttpTool post:ProductOp params:param success:^(id responseObj) {
        
        NSLog(@"+++++++++________%@", responseObj);
        NSLog(@"=====---------------%@", param);
        if ([[responseObj objectForKey:@"Err"] intValue]== 0) {
             [self commodityLibraryInformationDataRequest];
        }
    } failure:^(NSError *error) {
        
        
    }];
}
#pragma mark -- 下架或者上架
- (void)GroundingVC:(NSString *)ProductID{
    NSLog(@"下架");
    
    if ([[NNSingleton sharedSingleton].btnState isEqualToString:@"1"]) {
        NSDictionary *param = @{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN,@"ProductId":ProductID,@"Operation":@"下架" };
        
        [GDJHttpTool post:ProductOp params:param success:^(id responseObj) {
            
            NSLog(@"+++++++++________%@", responseObj);
            NSLog(@"=====---------------%@", param);
            if ([[responseObj objectForKey:@"Err"] intValue]== 0) {
                  [self commodityLibraryInformationDataRequest];
//             [_CommodityWView reloadData];
            }
            
           
        } failure:^(NSError *error) {
            
            
        }];
    }else if ([[NNSingleton sharedSingleton].btnState isEqualToString:@"3"]){
        
        NSLog(@"上架");
        
        NSDictionary *param = @{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN,@"ProductId":ProductID,@"Operation":@"上架" };
        
        [GDJHttpTool post:ProductOp params:param success:^(id responseObj) {
            
            NSLog(@"+++++++++________%@", responseObj);
            NSLog(@"=====---------------%@", param);
            if ([[responseObj objectForKey:@"Err"] intValue] == 0) {
                  [self commodityLibraryInformationDataRequest];
//                [_CommodityWView reloadData];
                
            }
        } failure:^(NSError *error) {
            
            
        }];

        
    }
  
}


#pragma mark -- 代理
//- (void)choiceButtonActionDelegate:(NSString*)indexPath
//{
//    [NNSingleton sharedSingleton].commodityLibraryID = [NSString stringWithFormat:@"%@",indexPath];
//    [NNSingleton sharedSingleton].releasePosition = @"商品库";
//    ReleaseCommodityViewController *releaseCommodity = [[ReleaseCommodityViewController alloc]init];
//    [self.navigationController pushViewController:releaseCommodity animated:YES];
//}
#pragma mark -- 获取商品库信息
- (void)commodityLibraryInformationDataRequest{
    
    [SVProgressHUD showWithStatus:@"正在加载"];
    
    
    NSLog(@"黄黄黄%@",[NNSingleton sharedSingleton].btnState);
    NSDictionary *prarm = @{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN,@"Statues":[NNSingleton sharedSingleton].btnState,@"Index":@"1",@"MaxId":@"0",@"Cid":[NNSingleton sharedSingleton].ERJIID};
    NSLog(@"%@",prarm);
    [GDJHttpTool get:ProductList params:prarm success:^(id responseObj) {
        NSLog(@"对面的女孩 %@",responseObj);
        //查看错误码
        NSInteger err = [[responseObj valueForKey:@"Err"]integerValue];
        NSLog(@"争取吧%ld",(long) err);
        if (err == 0) {
            
            _data_array =   [ProductModel mj_objectArrayWithKeyValuesArray:[responseObj objectForKey:@"Products"]];
        }
        if (_data_array.count != 0) {
            ProductModel * model = _data_array[0];
            
            //            [_CommodityWView reloadData];
            [self example21:[NSString stringWithFormat:@"%d",model.Id]];
        }
         [SVProgressHUD dismiss];
        [_CommodityWView reloadData];
        if(_data_array.count == 0){
            UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(self.center.x - 145,50, 120, 100)];
            image.image = [UIImage imageNamed:@"小哭脸"];
            [self addSubview:image];
            
            UILabel *imageLabel = [[UILabel alloc]init];
            imageLabel.frame = CGRectMake(0 , 170, kScrernWidth-90, 30);
            imageLabel.textAlignment = NSTextAlignmentCenter;
            imageLabel.textColor = [UIColor colorWithHue:0.00 saturation:0.00 brightness:0.33 alpha:1.00];
            imageLabel.font = [UIFont systemFontOfSize:13];
            imageLabel.text = @"商品中心中没有您要找的商品";
            [self addSubview:imageLabel];
        }else{
            [SVProgressHUD dismiss];
        }
        
    }failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}
#pragma mark -- 刷新加载数据
- (void)example21:(NSString *)MaID{
    __unsafe_unretained __typeof(self) weakSelf = self;
    NSLog(@"查询");
    //        weakSelf.storeListTableView.mj_header.hidden = NO;
    // 下拉刷新
    weakSelf->_CommodityWView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        //        pageNumber = 1;
        //        [self commodityLibraryInformationDataRequest];
        
        
        //        [weakSelf->_CommodityWView reloadData];
        // 结束刷新
        [weakSelf->_CommodityWView.mj_header endRefreshing];
        
    }];
    //    [weakSelf.sellCenterTableV.mj_header beginRefreshing];
    // 上拉刷新
    weakSelf->_CommodityWView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        pageNumber ++;
        [self requestDataListRefreshMore:[NSString stringWithFormat:@"%ld", (long)pageNumber ]:MaID];
        
        //        [weakSelf->_CommodityWView reloadData];
        // 结束刷新
        [weakSelf->_CommodityWView.mj_footer endRefreshing];
        
    }];
    // 默认先隐藏footer
    weakSelf->_CommodityWView.mj_footer.hidden = NO;
}
#pragma mark -- 请求下一页的数据
- (void)requestDataListRefreshMore:(NSString *)pageNumber1:(NSString *)MaxId{
    
    //    ChanelDataArray = [NSMutableArray array];
    _goodDataListRefresh = [NSMutableArray array];
    NSDictionary *prarm = @{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN,@"Statues":[NNSingleton sharedSingleton].btnState,@"Index":pageNumber1,@"MaxId":MaxId,@"Cid":[NNSingleton sharedSingleton].ERJIID};
    NSLog(@"%@", prarm);
    [GDJHttpTool get:ProductList params:prarm success:^(id responseObj) {
        NSLog(@"%@", responseObj);
        NSLog(@"%@", prarm);
        if ([[responseObj objectForKey:@"Err"] intValue]) {
            
        }else{
            
            _goodDataListRefresh =   [ProductModel mj_objectArrayWithKeyValuesArray:[responseObj objectForKey:@"Products"]];
            [_data_array addObjectsFromArray:_goodDataListRefresh];
            NSLog(@"+++++++%lu",(unsigned long)_data_array.count);
        }
        
        [_CommodityWView reloadData];
        //        [self example21:[NSString stringWithFormat:@"%d",model.Id]];
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"@@@@@@###   %ld",(long)indexPath.row);
    EditProductViewController *editProductVC = [[EditProductViewController alloc]init];
//    self.hidesBottomBarWhenPushed=YES;
    ProductModel *model  = _data_array[indexPath.row];
    editProductVC.ProductID =[NSString stringWithFormat:@"%d",model.Id] ;
    [self.navigationController pushViewController:editProductVC animated:YES];
}
#pragma mark -- 限制输入数字和小数点
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //控制长度
    if(range.location>=20)
        return NO;
    
    const char * ch=[string cStringUsingEncoding:NSUTF8StringEncoding];
    if(*ch == 0)
        return YES;
    //字符0－9 和 .
    if( *ch != 46 && ( *ch<48 || *ch>57) )
        return NO;
    
    //有了小数点
    if([textField.text rangeOfString:@"."].length==1)
    {
        NSUInteger length=[textField.text rangeOfString:@"."].location;
        
        //小数点后面两位小数 且不能再是小数点
        if([[textField.text substringFromIndex:length] length]>3 || *ch ==46)   //3表示后面小数位的个数。。
            
            return NO;
    }
    
    return YES;
    
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    
    return YES;
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end

